package netty.test2BioServer;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 1，启动服务端后 DOS窗口中通过  telnet 127.0.0.1 6666 连接到这个服务器
 * 2，通过  ctrl+]  然后按回车健   就可以发送数据了  比如发送hello 命令为 send hello
 *
 */
public class BIOServer {
    public static void main(String[] args) throws IOException {
        //当线程不够的时后，任务会放入线程池的排队队列中
        ExecutorService service= Executors.newSingleThreadExecutor();
        ServerSocket serverSocket=new ServerSocket(6666);
        System.out.println("BIOServer start.....");
        while(true){
           final Socket socket= serverSocket.accept();
            System.out.println("conect a client....");
            service.execute(new Runnable() {
                @Override
                public void run() {
                    handler(socket);
                }
            });
        }

    }

    public static void handler(Socket socket){
        try{
            System.out.println("current thread is "+Thread.currentThread().getId());
            byte [] bytes=new byte[1024];
            InputStream in=socket.getInputStream();

            while(true){
                //如果没有数据，线程就会阻塞在这里
                System.out.println("there will blocking..... thread="+Thread.currentThread().getId());
                int len=in.read(bytes);
                if(len !=-1){
                    System.out.println(new String(bytes));
                }else{
                    break;
                }
            }

        }catch (Exception e){
            System.out.println("server exception....");
            e.printStackTrace();
        }finally {
            System.out.println("finally excute.....");
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
